package com.sparrow.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import com.sparrow.enums.JALERT_TYPE;

public class JSUtil {
	/**
	 * 获取js的安全脚本
	 * 
	 * &apos;'单引号
	 * 
	 * &quot; " 双引号
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param str
	 * @return
	 */
	public static String getSafeJsString(String str) {
		if (str == null) {
			return null;
		} else {
			return str.replace("'", "&apos;").replace("\"", "&quot;")
					.replace("\r\n", "<br/>").replace("\n", "<br/>");
		}
	}

	/**
	 * javascript 弹出消息
	 * 
	 * @author zhanglizhi
	 * @date Jun 25, 2011
	 * @version 1.0
	 * @param msg
	 * @return
	 */
	public static String jalert(String msg, JALERT_TYPE jalert_type) {
		switch (jalert_type) {
		case LOCK:
			return String.format("jalert('%1$s','lock')", msg);
		case WAIT:
			return String.format("jalert('%1$s','wait')", msg);
		case SMILE:
			return String.format("jalert('%1$s','smile')", msg);
		case SAD:
			return String.format("jalert('%1$s','sad')", msg);
		default:
			return String.format("jalert('%1$s','smile')", msg);
		}
	}

	public static String alertClose(String msg, JALERT_TYPE jalert_type) {
		return msg;

	}

	/**
	 * 支持js decodeURIComponent
	 * 
	 * @author zhanglizhi
	 * @date Sep 24, 2011
	 * @version 1.0
	 * @param content
	 * @return
	 */
	public static String encodeURIComponent(String content) {
		try {
			if (StringUtil.isNullOrEmpty(content)) {
				return "";
			}
			return URLEncoder.encode(content, "UTF-8").replace("+", "%20");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 支持js encodeURIComponent
	 * 
	 * @author zhanglizhi
	 * @date 2012-11-10
	 * @version 1.0
	 * @param content
	 * @return
	 */
	public static String decodeURIComponent(String content) {
		try {
			return URLDecoder.decode(content, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	/**
	 * 通过js 设置5iEditor的编辑器内容
	 * 
	 * @author zhanglizhi
	 * @date Sep 10, 2011
	 * @version 1.0
	 * @param editorContent
	 * @param editor
	 * @return
	 */
	public static String get5iEditorContent(String editor,
			String editorContent, String attach) {
		return String
				.format("%1$s.initContent=function(){"
						+ "%1$s.setEditorContent(decodeURIComponent(\"%2$s\"));};"
						+ "%1$s.attach.setParentObject(%1$s);"
						+ "%1$s.config.attach.uploadedJson=decodeURIComponent('%3$s');",
						editor, encodeURIComponent(editorContent),
						encodeURIComponent(attach));
	}
}
